package com.ruoyi.wx.controller;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.wx.domain.MerchantVerification;
import com.ruoyi.wx.util.AddressResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.wx.domain.Merchant;
import com.ruoyi.wx.service.IMerchantService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 店铺信息Controller
 * 
 * @author wx
 * @date 2025-05-10
 */
@RestController
@RequestMapping("/merchant")
@CrossOrigin
public class MerchantController extends BaseController
{
    @Autowired
    private IMerchantService merchantService;

    /**
     * 查询店铺信息列表
     */
//    @RequiresPermissions("wx:merchant:list")
    @GetMapping("/list")
    public TableDataInfo list(Merchant merchant)
    {
        startPage();
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        return getDataTable(list);
    }

    /**
     * 根据mid查询店铺信息列表wwc
     */
//    @RequiresPermissions("wx:merchant:list")
    @GetMapping("/getMerchant")
    public R<?> getMerchant(MerchantVerification merchantVerification)
    {
        Merchant merchant = merchantService.selectMerchantByMId(merchantVerification.getMid());
        return R.ok(merchant);
    }

    /**
     * 导出店铺信息列表
     */
    @RequiresPermissions("wx:merchant:export")
    @Log(title = "店铺信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Merchant merchant)
    {
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        util.exportExcel(response, list, "店铺信息数据");
    }

    /**
     * 获取店铺信息详细信息
     */
    @RequiresPermissions("wx:merchant:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(merchantService.selectMerchantById(id));
    }

    /**
     * 新增店铺信息
     */
    @RequiresPermissions("wx:merchant:add")
    @Log(title = "店铺信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.insertMerchant(merchant));
    }

    /**
     * 新增店铺信息（注册）
     */
//    @RequiresPermissions("wx:merchant:add")
    @Log(title = "店铺信息", businessType = BusinessType.INSERT)
    @PostMapping("/addMerchant")
    public Merchant addMerchant(@RequestBody Merchant merchant) throws JsonProcessingException {
        String address = merchant.getAddress();
        String key = "TGPBZ-MUFL4-I54U7-KWAA3-K4MCE-EXB22";
        String url = "https://apis.map.qq.com/ws/geocoder/v1?address=" +
                URLEncoder.encode(address, StandardCharsets.UTF_8) +
                "&key=" + key;

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(URI.create(url), String.class);
        System.out.println(response); //返回的是json字符串
//        获取经纬度
        ObjectMapper mapper = new ObjectMapper();
        AddressResponse response1 = mapper.readValue(response, AddressResponse.class);

        if (response1 != null){
            double lat = response1.getResult().getLocation().getLat();
            String lat1 = lat + "";
            merchant.setLatitude(lat1); //设置纬度
            double lng = response1.getResult().getLocation().getLng();
            String lng1 = lng + "";
            merchant.setLongitude(lng1); //设置经度
            System.out.println(response1.getResult().getLocation().getLat());
            System.out.println(response1.getResult().getLocation().getLng());
        }
        merchant.setAuditStatusId(1L); //设置审核状态
        merchant.setRate(0L); //设置评分
        merchant.setStatus(0L); //设置店铺状态
        merchant.setRegTime(new java.util.Date()); //设置注册时间


        int i = merchantService.insertMerchant(merchant);
        return merchant;
    }

    /**
     * 修改店铺信息
     */
    @RequiresPermissions("wx:merchant:edit")
    @Log(title = "店铺信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Merchant merchant)
    {
        return toAjax(merchantService.updateMerchant(merchant));
    }

    /**
     * 删除店铺信息
     */
    @RequiresPermissions("wx:merchant:remove")
    @Log(title = "店铺信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(merchantService.deleteMerchantByIds(ids));
    }
}
